package com.example.demo.tool;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Component
public class RedisTool {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    public <T> T get(String key, Class<T> clazz) {
        Object cacheValue = redisTemplate.opsForValue().get(key);
        if (cacheValue != null) {
            return JSONObject.toJavaObject(JSONObject.parseObject(cacheValue.toString()), clazz);
        }
        return null;
    }

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
    }

    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), time, TimeUnit.SECONDS);
    }

    public void del(String key) {
        redisTemplate.delete(key);
    }

    // 增加计数
    public Long incrementCounter(String key,Integer value) {
        return redisTemplate.opsForValue().increment(key, value==null?1:value);  // 每次调用增加 1
    }

    // 获取计数
    public Long getCounter(String key) {
        return (Long) redisTemplate.opsForValue().get(key);  // 获取当前计数值
    }

}
